<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { useUserStore } from '@/stores/user'

import BiPopup from '@/components/bi-popup/index.vue'
import BiTaskCard from '@/components/bi-task-card/index.vue'

import { uploadTaskEventToGA, getCurrentClientTime, handleToEggOrLottery, Status } from '@/utils'
import { todayTask, game } from '@/mock/index'
import { fetchGetReward, uploadTaskEventToAdmin, fetchGameTask } from '@/api/task.ts'
import { uploadViewAdType } from '@/api/ad'

const userStore = useUserStore()
const router = useRouter()

const todayTaskList = reactive(todayTask)
const todayTaskLoading = ref(true)
const userInfo = ref(userStore.info)

userStore.$subscribe((_mutation, state) => {
    if (Object.keys(state.info).length > 0) {
        userInfo.value = state.info
        handleGetTodayTaskInfo()
    }
})

const handleGetTodayTaskInfo = () => {
    // 砸蛋
    todayTaskList.egg.finishCount = userInfo.value.turntableNums
    todayTaskList.egg.taskCount = userInfo.value.turntableTotalNums

    // 转盘
    todayTaskList.lottery.finishCount = userInfo.value.lotteryNums
    todayTaskList.lottery.taskCount = userInfo.value.lotteryTotalNums

    // 观看三次插屏广告
    todayTaskList.slot.finishCount = userInfo.value.viewInsertScreenAdNum
    todayTaskList.slot.isReceive = userInfo.value.viewIsGetChalice
    // 浏览30秒网页
    todayTaskList.thirty.isReceive = userInfo.value.pageStayIsGetChalice
    todayTaskList.thirty.isComplete = userInfo.value.finishPageStay
    if (todayTaskList.thirty.isComplete == 1) {
        todayTaskList.thirty.finishCount = 1
    }

    // 个人信息加载才展示今日任务按钮
    todayTaskLoading.value = false
}
handleGetTodayTaskInfo()

interface TodayTask {
    finishCount: number,
    taskCount: number,
    repeat: boolean,
    isReceive?: number,
    isComplete?: number,
    rewardNum?: number
}

const taskStatus = (task: TodayTask, type: string) => {
    const notCount = task.finishCount === task.taskCount
    const unReceive = task.isReceive == 2
    const notBrowseThirtySec = type != 'thirty'

    if ((notCount && unReceive) || task.repeat) {
        return Status.unReceive
    }

    if (notCount && !task.repeat && notBrowseThirtySec) {
        return Status.isComplete
    }
}

const gameInfo = ref(game)
const handleFetchGameTask = async () => {
    try {
        const res = await fetchGameTask({ device: userStore.device })

        gameInfo.value.finishedNum = res.data.data.gameTaskVOList.length
        const allTaskfinish = gameInfo.value.finishedNum == gameInfo.value.total

        gameInfo.value.isComplete = allTaskfinish ? 1 : 2

        if (allTaskfinish && res.data.data.gameStepsIsGetChalice) {
            gameInfo.value.isReceive = 1
        }
    } catch (error) {

    }
}
handleFetchGameTask()

enum GameStatus {
    finish = 0,
    unReceive = 1
}
const gameStatus = computed(() => {
    if (gameInfo.value.isComplete == 1 && gameInfo.value.isReceive == 2) {
        return GameStatus.unReceive
    }

    if (gameInfo.value.isComplete == 1 && gameInfo.value.isReceive == 2) {
        return GameStatus.finish
    }
})

const showGamePopup = ref(false)
const openGamePopup = () => {
    showGamePopup.value = true
}
const closeGamePopup = () => {
    showGamePopup.value = false
}
let fnType = ''
const operationGameFn = () => {
    if (gameInfo.value.isComplete == 2 || gameInfo.value.isReceive == 1) {
        uploadTaskEventToAdmin({
            device: userStore.device,
            moduleType: 3,
            eventType: gameInfo.value.goId
        })
        uploadTaskEventToGA(gameInfo.value.name)

        router.push({
            path: '/game',
            query: {
                gameId: gameInfo.value.gameId
            }
        })
        return
    }

    if (gameInfo.value.isComplete == 1 && gameInfo.value.isReceive == 2) {
        if (android.taskShowInter) {
            // 判断是什么类型的东西触发了广告
            fnType = 'game'
            android.taskShowInter()
        } else {
            openGamePopup()
        }
    }
}

onMounted(() => {
    window.handleCommonCallback = () => {
        try {
            if (fnType == 'game') {
                openGamePopup()
                return
            }
        } catch (e) {
            console.log(e)
        }
    }
})

const adsRewardPopup = ref(false)
const openAdsRewardPopup = () => {
    adsRewardPopup.value = true
}

interface NeedReward {
    id: number,
    rewardNum: number,
    gaName: string,
    informationId?: number,
    gameId?: number
}

const currentRewardNum = ref(0)
const handleGetRewards = async (task: NeedReward) => {
    currentRewardNum.value = task.rewardNum
    try {
        await fetchGetReward({
            deviceInfo: userStore.device,
            remarks: task.gaName,
            pointsType: task.id,
            points: task.rewardNum,
            informationId: task.informationId,
            gameId: task.gameId
        })
        if (task.id === 38) {
            todayTaskList.thirty.isReceive = 1
        }
        if (task.id === 39) {
            todayTaskList.slot.isReceive = 1 // 1是已领取圣杯，2是未领取圣杯
        }
        showToast('Receive successfully');
        if (task.id == 37) {
            closeGamePopup()
        } else {
            openAdsRewardPopup()
        }

        userStore.handleGetUserInfo()
    } catch (error) {
        throw new Error(error as string)
    }
}

const handleUploadAdViewType = async (adType: number) => {
    try {
        await uploadViewAdType({ device: userStore.device, adType, viewingTime: getCurrentClientTime() })
    } catch (error: any) {
        throw new Error(error)
    }
}

const handleTaskMethods = (task: any) => {
    const unCompleted = task.taskCount > task.finishCount
    if (!task.repeat && task.isReceive == 2 && !unCompleted) {
        handleGetRewards(task)
        return
    }
    // 观看三次插屏广告
    if (task.goId == 30 && task.isReceive != 1) {
        handleUploadAdViewType(5)
    }
    if (task.repeat || unCompleted || (task.isReceive == 1 && task.goId != 30)) {
        try {
            uploadTaskEventToAdmin({
                device: userStore.device,
                moduleType: 2,
                eventType: task.goId
            })
            uploadTaskEventToGA(task.gaName)
            task.fn(userStore.device)
        } catch (error) {
            console.log(error)
        }
    }
}

const hideCount = (id: string) => {
    return id === '8'
}
</script>

<template>
    <div class="box">
        <div class="box-title">
            <span style="font-size: 5.2vmin;">Today Task</span>
        </div>
        <ul class="list">
            <li>
                <BiTaskCard @btn-click="operationGameFn" :name="gameInfo.taskName" type="flame" :icon="gameInfo.imgUrl"
                    icon-size="100%" :finish-count="gameInfo.finishedNum" :total-count="gameInfo.total"
                    :status="gameStatus" :num="300" />
            </li>
            <li v-for="(task, type) in todayTaskList" :key="task.goId">
                <BiTaskCard @btn-click="handleTaskMethods(task)" :name="task.name" :icon="task.imgUrl"
                    :type="task.awardType" :finish-count="task.finishCount" :total-count="task.taskCount"
                    :status="taskStatus(task, type)" :hide-count="hideCount(task.goId)" :num="task.rewardNum"
                    :hideNum="task.rewardNum <= 0" />
            </li>
        </ul>

        <!-- 获取观看三次广告奖励弹窗 -->
        <BiPopup v-model:show="adsRewardPopup" @click="handleToEggOrLottery" rewards-type="flame"
            :rewards-num="currentRewardNum">
        </BiPopup>

        <!-- 获取游戏奖励的弹窗 -->
        <BiPopup v-model:show="showGamePopup" :rewards-num="300" rewards-type="flame"
            @click="handleGetRewards({ id: 37, rewardNum: 300, gaName: '完成六个游戏步骤', gameId: 2372 })"
            button-text="Get Wheats">
        </BiPopup>

    </div>
</template>

<style scoped lang="scss">
.box-title {
    span {
        font-size: var(--mini-font-size);
    }
}

.list {
    background-color: #fff;
    padding: 6vmin 3vmin;

    li {
        margin-bottom: 3vmin;

        &:last-child {
            margin-bottom: 0
        }
    }
}
</style>